import { getToken, removeToken, setToken } from '@/utils/auth'
import { getProfile, getUserDetailById, login } from '@/api/user'
export default {
  namespaced: true,
  state: {
    token: getToken() || null,
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken(state, newToken) {
      state.token = newToken // 设置token
      setToken(newToken)
    },
    // 删除token
    removeToken(state) {
      state.token = null // 删除vuex的token
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 删除用户信息
    reomveUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async getToken(context, loginForm) {
      const res = await login(loginForm)
      context.commit('setToken', res.data)
      return res
    },
    async getUserInfo(context) {
      const res = await getProfile()
      const res1 = await getUserDetailById(res.data.userId)
      context.commit('setUserInfo', { ...res.data, ...res1.data })
    },
    layout(context) {
      context.commit('reomveUserInfo')
      context.commit('removeToken')
    }
  }
}
